package com.org.devg.monitor.server.api;

import com.alibaba.fastjson.JSONObject;
import com.org.devg.monitor.common.Common;
import com.org.devg.monitor.common.DevgRabbit;
import com.org.devg.monitor.server.api.service.WeChatMessageService;
import com.org.devg.monitor.server.model.MonitorServerConfig;
import org.devgframwork.platform.model.ResultModel;
import org.devgframwork.rabbitmq.DevgRabbitProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(value = Common.serverConfigUrl, tags = "监控配置")
@Slf4j
@RestController
public class MonitorServerController {

    @Resource
    private DevgRabbitProperties devgRabbitProperties;

    @Resource
    private WeChatMessageService weChatMessageService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MonitorServerConfig monitorServerConfig;

    @ApiOperation("获取监控配置")
    @GetMapping(value = {Common.serverConfigUrl})
    public ResultModel getServerConfig() {
        DevgRabbit devgRabbit = new DevgRabbit();
        BeanUtils.copyProperties(devgRabbitProperties, devgRabbit);
        Long nodeNumber = stringRedisTemplate.opsForValue().increment(Common.nodeNumber);
        stringRedisTemplate.expire(Common.nodeNumber, 24, TimeUnit.HOURS);
        Map<String, Object> result = new HashMap<>();
        result.put(Common.rabbitmqConfig, devgRabbit);
        result.put(Common.nodeNumber, nodeNumber);
        result.put(Common.showStackTraceMsg, monitorServerConfig.getShowStackTraceMsg());
        return ResultModel.newSuccess(result);
    }

    @RequestMapping("/wechat/robotMsg")
    public ResultModel robotMsg(@RequestParam("msg") String msg) throws Exception {
        ResultModel<String> result = weChatMessageService.sendText(msg);
        log.info("wechat:robotMsg:{}", JSONObject.toJSONString(result));
        return result;
    }

}
